package com.gxg.services;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Service;

@Service
public class CheckCodeService
{
  public void createCheckCode(HttpServletRequest request, HttpServletResponse response)
  {
    response.setDateHeader("Expires", -1L);
    response.setHeader("Cache-Control", "no-cache");
    response.setHeader("Pragma", "no-cache");
    
    response.setHeader("Content-Type", "image/jpeg");
    
    BufferedImage image = new BufferedImage(80, 30, 1);
    
    Graphics g = image.getGraphics();
    
    g.setColor(Color.WHITE);
    g.fillRect(0, 0, 80, 30);
    
    g.setColor(Color.BLACK);
    g.setFont(new Font(null, 1, 20));
    
    String num = makeNum();
    request.getSession().setAttribute("checkCode", num);
    g.drawString(num, 0, 20);
    try
    {
      ImageIO.write(image, "jpg", response.getOutputStream());
    }
    catch (IOException e)
    {
      e.printStackTrace();
    }
  }
  
  private String makeNum()
  {
    Random r = new Random();
    String num = r.nextInt(9999) + "";
    StringBuffer stringBuffer = new StringBuffer();
    for (int i = 0; i < 4 - num.length(); i++) {
      stringBuffer.append("0");
    }
    num = stringBuffer.toString() + num;
    return num;
  }
}
